<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>三人对战</title>
    <script th:src="jquery-3.5.1.min.js"></script>
</head>

<body>
<!--显示当前房间信息-->
<p id="roomId"></p>
<hr>

<!--显示玩家信息-->
<div id="playerInfo" style="display:none">
</div>


<div id="result1" style="display:none">
    本回合结果：<div id="result"></div>
</div>


<div id="attackArea" style="display:none">
    <select id="attackWay" lay-verify="" >
        <option value="">请选择一个攻击招式</option>
        <option value="yun">运</option>
        <option value="dang0">挡</option>
        <option value="dang1">一气挡</option>
        <option value="biao">小标</option>
        <option value="adugen">阿杜跟</option>
    </select>

    <select id="attackPlayer" lay-verify="" >
        <option value="">请选择一个攻击目标</option>
    </select>
    <button id="sendAttackMsg" onclick="sendAttackMsg()">确定攻击</button>
</div>


<div>
    <button onclick="closeWebSocket()">退出房间</button>
    <button id="nextGame" onclick="nextGame()">准备下一局</button>
    <hr/>
    <br/>

    消息：<input id="text" type="text" />
    请输入私聊玩家名：<input id="toUser" type="text" />
    <button onclick="send()">发送消息</button>

</div>
<hr>

<div id="message" style="border: 1px"></div>




<!--    -&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;-->
<script type="text/javascript">
    //id
    var En = ['A','B','C','D','E'];

    //获取创建房间的传值
    window.getQueryString = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }
    var roomid=getQueryString("roomid");
    var playerName=getQueryString("playerName");
    var playerNum=getQueryString("playerNum");
    $('#roomId').html("当前房间号： "+roomid+"    当前用户： "+playerName+"    几人场： "+playerNum);

    var websocket = null;
    var mynickname = null;


    //页面刷新自动连接
    $(document).ready(function(){
        playerInit();

        mynickname = playerName;

        //判断当前浏览器是否支持WebSocket
        if (!websocket){
            if ('WebSocket'in window) {
                websocket = new WebSocket("ws://localhost:8080/chat/" + playerName + "/"+roomid + "/"+playerNum);
            } else {
                alert('Not support websocket')
            }
        }else {
            alert('同一个客户端重复连接')
        }


        //连接发生错误的回调方法
        websocket.onerror = function() {
            setMessageInnerHTML("error");
        };

        //连接成功建立的回调方法
        websocket.onopen = function(event) {
            setMessageInnerHTML("Loc MSG: 成功建立连接");
        };

        //接收到消息的回调方法
        websocket.onmessage = function(event) {
            let rsvMsg = JSON.parse(event.data);

            //聊天内容
            if (rsvMsg.msgType === "chat"){
                setMessageInnerHTML(rsvMsg.content);
            }
            //回合结果
            if (rsvMsg.msgType === "gameMsg"){
                document.getElementById('result').innerHTML += rsvMsg.content + '<br/>';
            }
            //更新玩家名字信息，并显示几个隐藏区域
            if (rsvMsg.msgType === "UpdatePlayerNameMap"){
                $('#playerInfo').show();
                $('#result1').show();
                $('#attackArea').show();

                for (let i=0;i<playerNum;i++){
                    document.getElementById('player'+En[i]).value = rsvMsg["player"+i];
                    $("#attackPlayer").append("<option value='" + rsvMsg["player"+i] + "'>"+rsvMsg["player"+i] + "</option>");
                    console.log(rsvMsg["player"+i])
                }
            }
            //更新玩家血量
            if (rsvMsg.msgType === "UpdatePlayerBlood"){
                $("#sendAttackMsg").removeAttr("disabled","disabled");
                for (let i=0;i<playerNum;i++){
                    let name = document.getElementById('player'+En[i]).value;
                    document.getElementById('blood'+En[i]).value = rsvMsg[name];
                }
            }
            //更新玩家的气
            if (rsvMsg.msgType === "UpdatePlayerQi"){
                for (let i=0;i<playerNum;i++){
                    let name = document.getElementById('player'+En[i]).value;
                    document.getElementById('qi'+En[i]).value = rsvMsg[name];
                }
            }
            //血量为0，禁用按钮
            if (rsvMsg.msgType === "bloodZero"){
                $("#sendAttackMsg").attr("disabled","disabled");
                setMessageInnerHTML(rsvMsg.content);
            }
            //全部准备，重新开始下一局
            if (rsvMsg.msgType === "readyMsg"){
                $("#nextGame").removeAttr("disabled","disabled");
                $("#sendAttackMsg").removeAttr("disabled","disabled");
                document.getElementById('result').innerHTML += '全部准备，重新开始下一局' + '<br/>';
                document.getElementById('result').innerHTML += rsvMsg.content + '<br/>';
                setMessageInnerHTML("全部准备，重新开始下一局");
                for (let i=0;i<playerNum;i++){
                    document.getElementById('qi'+En[i]).value = 0;
                    document.getElementById('blood'+En[i]).value = 1;
                }

                // window.location.href="/threeGame?roomid="+roomid+"&playerName="+playerName+"&playerNum="+playerNum;
                // $(document).ready(function(){
                //     document.getElementById('result').innerHTML += '全部准备，重新开始下一局' + '<br/>';
                //     document.getElementById('result').innerHTML += rsvMsg.content + '<br/>';
                // });
            }
        };

        //连接关闭的回调方法
        websocket.onclose = function() {
            setMessageInnerHTML("Loc MSG:关闭连接");
        };

        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function() {
            websocket.close();
        };
    });


    //将消息显示在网页上
    function setMessageInnerHTML(innerHTMLtext) {
        document.getElementById('message').innerHTML += innerHTMLtext + '<br/>';
    }

    //关闭连接
    function closeWebSocket() {
        websocket.close();
        window.location.href="/room";
    }

    //发送消息
    function send() {
        var message = document.getElementById('text').value;
        var toUser = document.getElementById('toUser').value;
        var socketMsg = {
            msg: message,
            toUser: toUser
        };

        if (toUser === ''){
            //群聊.
            socketMsg.type = 0;
        }else{
            //单聊.
            socketMsg.type = 1;
        }

        let map = {
            msgType: "chat",
            sMsg: socketMsg
        };

        // websocket.send(JSON.stringify(socketMsg));
        websocket.send(JSON.stringify(map));

        // websocket.send(message);
    }


    //发送攻击信息
    function sendAttackMsg() {


        var attackWay = document.getElementById('attackWay').value;
        var attackUser = document.getElementById('attackPlayer').value;

        //攻击目标不能是自己
        if(attackUser===mynickname){
            alert("攻击目标不能是自己");
            return;
        }
        //运和挡不能选择攻击目标
        if(attackWay==='yun' || attackWay==='dang0' || attackWay==='dang1'){
            if (attackUser !== ""){
                alert("运和挡不能选择攻击目标");
                return;
            }
        }

        var blood;
        var qi;
        for (let i=0;i<playerNum;i++){
            if(document.getElementById('player'+En[i]).value === mynickname){
                blood = document.getElementById('blood'+En[i]).value;
                qi = document.getElementById('qi'+En[i]).value;
            }
        }

        var attackMsg = {
            attackName: attackWay,
            attackUser: attackUser,
            blood: blood,
            qi: qi
        };

        let map = {
            msgType: "gameMsg",
            gMsg: attackMsg
        };

        websocket.send(JSON.stringify(map));

        //攻击一次不能再攻击
        $("#sendAttackMsg").attr("disabled","disabled");
    }

    //下一局
    function nextGame() {
        $("#nextGame").attr("disabled","disabled");

        let map = {
            msgType: "readyMsg",
            readyMsg: mynickname
        };

        websocket.send(JSON.stringify(map));

    }

    //按照房间人数初始化
    function playerInit() {
    // <div id="player2" style="display:none">
    //      <input id="playerC" type="text" value="自己" disabled>： <br>
    //      血量：<input id="bloodC" type="text" value=1 disabled><br>
    //      气：<input id="qiC" type="text" value=0 disabled>
    // </div>

        for (let i=0; i<playerNum;i++){
            let txt1="<div id='player'"+i +">";
            let txt2="<input id='player"+En[i] +"' type='text' value='' disabled>： <br>";
            let txt3="血量：<input id='blood"+En[i] +"' type='text' value=1 disabled><br>";
            let txt4="气：<input id='qi"+En[i] +"' type='text' value=0 disabled>";
            let txt5="</div>";
            $('#playerInfo').append(txt1,txt2,txt3,txt4,txt5);
        }
    }

</script>

</body>
</html>